/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.com.jr2tecnologia;

import br.com.jr2tecnologia.model.LoginPersistenceLocal;
import br.com.jr2tecnologia.model.entity.Login;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author ronildo
 */
public class SecurityFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger();

    @EJB
    private LoginPersistenceLocal loginFacade;
    private FilterConfig filterConfig;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        Object user = request.getSession().getAttribute(ConstantsOfSystem.USER_SESSION_KEY);
        String resource = request.getRequestURI().replaceAll(request.getContextPath(), "");

        try{
            if (user == null || !loginFacade.loginHasPermissionForResource((Login) user, resource)) {
                logger.info("acesso ao recurso negado: " + resource);
                response.sendRedirect(ConstantsOfSystem.LNK_DENIED_PERMISSION);
                return;
            }else
                logger.info("acesso ao recurso liberado: " + resource);
        }catch(RuntimeException ex){
            logger.info("Não foi possivel verificar as suas permissões de usuário");
        }

        try{
            chain.doFilter(request, response);
        }catch(Exception ex){
            logger.log(Level.SEVERE, ex.getMessage(), ex);
            response.sendRedirect(ConstantsOfSystem.LNK_ERROR);
        }
    }

    public void destroy() {
    }

    protected FilterConfig getFilterConfig() {
        return filterConfig;
    }
}
